package com.bw.goods_module.home;

import android.os.Bundle;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.databinding.ObservableField;
import androidx.viewpager.widget.ViewPager;

import com.bw.common.mvvm.viewmodel.BaseViewModel;
import com.bw.goods_module.R;
import com.bw.goods_module.home.adapter.GoodsAdapter;
import com.bw.goods_module.home.adapter.MenuAdapter;
import com.bw.network_sdk.BaseEntity;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

public class HomeViewModel extends BaseViewModel<HomeRepository>
        implements ViewPager.PageTransformer,
        OnRefreshLoadMoreListener, OnItemClickListener {

    private long categoryId = 14;
    private int pageNo = 1;
    //首页菜单虚拟数据
    private int[]menuIcons = {R.drawable.ic_zhibo,R.drawable.ic_diannao,
            R.drawable.ic_shouji,R.drawable.ic_pad,R.drawable.ic_jiaju,
            R.drawable.ic_jiadian,R.drawable.ic_yundong,R.drawable.ic_xiuxian};
    private String[] menuNames = {"直播","电脑","手机","Pad",
            "家居","家电","秒杀","休闲"};
    public List<HomeMenuEntity> menues = new ArrayList<>();
    //首页banner虚拟数据
    private String[]homeBanneres={"https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=259364631,2307942273&fm=26&gp=0.jpg",
            "https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=3765821666,4235344830&fm=26&gp=0.jpg",
            "https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=3336810809,2729597475&fm=26&gp=0.jpg",
            "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1503471047&di=679d7a6c499f59d1b0dcd56b62a9aa6c&imgtype=jpg&er=1&src=http%3A%2F%2Fimg.90sheji.com%2Fdianpu_cover%2F11%2F14%2F64%2F55%2F94ibannercsn_1200.jpg"};
    public List<HomeBannerEntity>homeBannerEntities = new ArrayList<>();
    //首页公告虚拟数据
    public List<String> txtBanneres = new ArrayList<>();
    //热门商品虚拟数据
    public List<String>hotImges = new ArrayList<>();
    //抢先行动虚拟数据
    public List<HomeBannerEntity>topEntities = new ArrayList<>();
    //首页HomeGoods数据源
    public ObservableField<List<GoodsEntity>>homeGoods=new ObservableField<>();
    //推荐的viewpager中最大以及最小缩放
    private static final float MAXSCALE = 1f;
    private static final float MINSCALE = 0.7f;

    @Override
    public void onResult(BaseEntity entity) {
        //由于当前ViewModel中统一订阅管理了Observer<BaseEntity>任务类型
        //当前页面下拉刷新或上拉加载返回值类型相同->无法区分当前数据具体返回值类型
        //从而导致刷新以及加载分页数据逻辑混乱
        //解决方式:发起请求时通过dialog阻塞用户在UI层级得其他操作->必须本次请求完成->下一步操作
        //        相当于在UI线程等待了本次网络请求;
        //        给上拉加载单独添加一个观察者任务，上拉加载时使用单独得观察者任务进行处理
        //        OK由于任务处理结果使用instance来区分任务类型->单独配置上来加载实体->指定为其他类型
        //        发起请求时传递一个变量到请求中，根据变量值，在返回值中添加额外参数，根据额外参数区分刷新以及加载

        if (entity instanceof HomeEntity){
            HomeEntity homeEntity = (HomeEntity) entity;
            homeGoods.set(homeEntity.data);
        }else if (entity instanceof HomeLoadEntity){
            HomeLoadEntity homeEntity = (HomeLoadEntity) entity;
            if (homeEntity.data == null)
                return;
            if (homeEntity.data.size() == 0)
                return;
            //数据拼接
            List<GoodsEntity> list = new ArrayList<>();
            list.addAll(homeGoods.get());
            list.addAll(homeEntity.data);
            homeGoods.set(list);
        }
    }

    //第一次进入当前界面数据请求
    @Override
    protected void initData() {
        //构建创建menu虚拟数据
        initMenu();
        //构建Banner虚拟数据
        initBanner();
        //构建公告虚拟数据
        initTextBanner();
        //构建热门商品虚拟数据
        initHot();
        Map<String,Object>map = new HashMap<>();
        map.put("categoryId",categoryId);
        map.put("pageNo",pageNo);
        respository.requestGoods(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(this);
    }

    //创建首页menu数据
    private void initMenu(){
        for (int i = 0; i <menuIcons.length;i++){
            menues.add(new HomeMenuEntity(menuIcons[i],menuNames[i],""));
        }
    }

    //创建Banner数据
    private void initBanner(){
        for (int i = 0;i < homeBanneres.length;i ++){
            homeBannerEntities.add(new HomeBannerEntity(homeBanneres[i],
                    "https://www.baidu.com/"));
            topEntities.add(new HomeBannerEntity(homeBanneres[i],
                    "https://www.baidu.com/"));
        }
    }

    //创建公告虚拟数据
    private void initTextBanner(){
        for (int i = 0;i < 5;i ++){
            txtBanneres.add("施源"+i);
        }
    }

    //创建热门商品虚拟数据
    private void initHot(){
        for (int i = 0;i < homeBanneres.length;i ++){
            hotImges.add(homeBanneres[i]);
        }
    }

    @Override
    public void transformPage(@NonNull View page, float position) {
        if (position == 0){
            //处于当前页
            page.setScaleY(MAXSCALE);
        }else if (position<0){
            //处于上一页->左侧
            float scale = 1+position;
            if (scale < MINSCALE)
                scale = MINSCALE;
            if (scale>MAXSCALE)
                scale = MAXSCALE;
            page.setScaleY(scale);
        }else if(position >0 && position <1){
            //处于下一页->右侧第一页
            float scale = MINSCALE+(1-position);
            if (scale < MINSCALE)
                scale = MINSCALE;
            if (scale>MAXSCALE)
                scale = MAXSCALE;
            page.setScaleY(scale);
        }else {
            //下下页->右侧第二页
            page.setScaleY(MINSCALE);
        }

    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        refreshLayout.finishLoadMore();
        pageNo += 1;
        Map<String,Object>map = new HashMap<>();
        map.put("categoryId",categoryId);
        map.put("pageNo",pageNo);
        respository.requestLoadGoods(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(this);
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        refreshLayout.finishRefresh();
        pageNo = 1;
        Map<String,Object>map = new HashMap<>();
        map.put("categoryId",categoryId);
        map.put("pageNo",pageNo);
        respository.requestGoods(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(this);
    }

    @Override
    public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        if (adapter instanceof MenuAdapter){
            //校验是否为秒杀
            if (position == (adapter.getData().size()-2))
                //跳转秒杀
                startPage("/seckill/seckilllistactivity");
            return;
        }
        GoodsAdapter goodsAdapter = (GoodsAdapter) adapter;
        Bundle bundle = new Bundle();
        bundle.putLong("goodsid",goodsAdapter.getData().get(position).id);
        bundle.putLong("categoryid",categoryId);
        startBundPage("/home/detailactivity",bundle);
    }
}
